package setting

import (
	"backend/pkg/logging"
	"fmt"
	"github.com/go-ini/ini"
	"log"
	"time"
)

var (
	Cfg *ini.File

	RunMode      string
	HTTPPort     int
	ReadTimeout  time.Duration
	WriteTimeout time.Duration

	PageSize  int
	JwtSecret string
	Appid     string
	Secret    string
	RedisConfig string
	RandCode string
	FeedBackId string
)

func init() {
	var err error
	Cfg, err = ini.Load("src/backend/conf/app.ini")
	if err != nil {
		fmt.Println(err)
	}

	loadBase()
	loadServer()
	loadApp()
	loadWeixin()
	loadRedis()
	loadRand()
	loadWxTpl()
}

func loadBase() {
	RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")
}

func loadServer() {
	sec, err := Cfg.GetSection("server")
	if err != nil {
		log.Fatal("get server section fail:", err)
	}

	RunMode = Cfg.Section("").Key("RUN_MODE").MustString("debug")

	HTTPPort = sec.Key("HTTP_PORT").MustInt(8080)
	ReadTimeout = time.Duration(sec.Key("READ_TIMEOUT").MustInt(60)) * time.Second
	WriteTimeout = time.Duration(sec.Key("WRITE_TIMEOUT").MustInt(60)) * time.Second
}

func loadApp() {
	sec, err := Cfg.GetSection("app")
	if err != nil {
		log.Fatal("load app section fail", err)
	}

	PageSize = sec.Key("PAGE_SIZE").MustInt(10)
	JwtSecret = sec.Key("JWT_SECRET").MustString("debug")
}

func loadWeixin() {
	sec, err := Cfg.GetSection("weixin")
	if err != nil {
		logging.Fatal(err)
	}

	Appid = sec.Key("APPID").MustString("")
	Secret = sec.Key("SECRET").MustString("")
}

func loadRedis() {
	sec, err := Cfg.GetSection("redis")
	if err != nil {
		logging.Fatal(err)
	}

	RedisConfig = sec.Key("HOST_REDIS").MustString("")
}

func loadRand() {
	sec, err := Cfg.GetSection("randcode")
	if err != nil {
		logging.Fatal(err)
	}

	RandCode = sec.Key("RAND").MustString("")
}

func loadWxTpl() {
	sec, err := Cfg.GetSection("wxtplid")
	if err != nil {
		logging.Fatal(err)
	}

	FeedBackId = sec.Key("FEEDBACK").MustString("")
}
